import re
import tool
import os
import urllib2
import log
from bs4 import BeautifulSoup

class Multiple:
    def __init__(self, url = '', dir = '', tag = u'undefined', opener = None):
        self.opener = opener
        self.dir = dir
        self.tag = tag
        self.tool = tool.Tool()
        self.log = log.Log()
        self.url = self.tool.removesomething('http://www.pixiv.net' + url)
        self.pid = re.search(re.compile('(\d+)', re.S), self.url)
        self.pid = self.pid.group(1)
        self.download_pic()

    def download_pic(self):
        bs = BeautifulSoup(self.opener.open(self.url),"html.parser")
        result_pic_more = re.search(re.compile('</li><li>.*?\s(.*?)P</li>', re.S),
                                    str(bs.find_all("ul", class_="meta")))
        for j in range(0, int(result_pic_more.group(1))):
            make_url = self.tool.make_big_url(self.url) + '&page=' + str(j)
            try:
                m_soup = BeautifulSoup(self.opener.open(make_url), "html.parser")
                real_url = re.search(re.compile('<img.*?src="(.*?)"/>', re.S), str(m_soup.find_all("img")))
                real_url = real_url.group(1)
                p_type = self.tool.Pic_Type(real_url)
                save_dir = self.dir + '/pixiv_' + self.pid + '_' + str(j) + '.' + p_type
                print save_dir
                if not os.path.exists(save_dir):
                    file_pic = open(save_dir, 'wb')
                    file_pic.write(self.download_request(make_url,real_url))
                    file_pic.close()
                else:
                    print 'The picture is exist, Skip Skip'
            except Exception,e:
                print e
                self.log.error_log(self.tag,self.pid, self.url)


    def download_request(self,make_url, real_url):
        p_download_header = {
            'Accept-Language': 'zh-CN,zh;q=0.8',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0'
        }
        p_download_header['Referer'] = self.tool.removebig(make_url)
        download_request = urllib2.Request(url=real_url,
            headers=p_download_header)
        decode_url = self.opener.open(download_request)
        return decode_url.read()